package com.meibao.item.service;

import com.meibao.common.enums.ExceptionEnums;
import com.meibao.common.exception.MbException;
import com.meibao.item.mapper.SpecGroupMapper;
import com.meibao.item.mapper.SpecParamMapper;
import com.meibao.item.pojo.SpecGroup;
import com.meibao.item.pojo.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SpecificationService {

    @Autowired
    private SpecGroupMapper specGroupMapper;
    @Autowired
    private SpecParamMapper specParamMapper;

    public List<SpecGroup> queryGroupByCid(Long cid) {
        //查询条件
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(cid);
        //查询
        List<SpecGroup> specGroupList = specGroupMapper.select(specGroup);
        if(CollectionUtils.isEmpty(specGroupList)){
            //没查到
            throw new MbException(ExceptionEnums.SPEC_GROUP_NOT_FIND);
        }
        return specGroupList;
    }

    public List<SpecParam> queryParamList(Long gid,Long cid, Boolean searching) {
        SpecParam specParam = new SpecParam();
        specParam.setGroupId(gid);
        specParam.setCid(cid);
        specParam.setSearching(searching);

        List<SpecParam> specParamList = specParamMapper.select(specParam);
        if(CollectionUtils.isEmpty(specParamList)){
            throw new MbException(ExceptionEnums.SPEC_PARAM_NOT_FIND);
        }
        return specParamList;
    }

    public List<SpecGroup> queryAllByCid(Long cid) {
        //查询规格组
        List<SpecGroup> specGroups = queryGroupByCid(cid);
        //查询组内参数
        List<SpecParam> specParams = queryParamList(null, cid, null);

        //先把组内参数变成map id为组id   值为参数集合
        Map<Long, List<SpecParam>> map = new HashMap<>();
        for (SpecParam param : specParams) {
            if (!map.containsKey(param.getGroupId())) {
                map.put(param.getGroupId(), new ArrayList<>());
            }
            map.get(param.getGroupId()).add(param);
        }
        //填充param到group
        for (SpecGroup specGroup : specGroups) {
            specGroup.setParams(map.get(specGroup.getId()));
        }
        return specGroups;
    }
}
